﻿using Microsoft.IdentityModel.Tokens;
using PlayingCards.Model.Conf;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace PlayingCards.Comm.Extensions
{
    public static class StringExtension
    {
        /// <summary>
        ///  生成token
        /// </summary>
        /// <param name="UserName">唯一标识</param>
        /// <param name="jwt">参数</param>
        /// <param name="sid"></param>
        /// <param name="groupSid"></param>
        /// <returns></returns>
        public static string GetJwtToken(string UserName, JWTToken jwt)
        {
            //Payload,存放用户信息
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,UserName)
            };
            //取出私钥并以utf8编码字节输出
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecurityKey));
            var jwtToken = new JwtSecurityToken(
                issuer: jwt.Issuer,
                audience: jwt.Audience,
                claims: claims,
                //notBefore: DateTime.UtcNow,
                expires: DateTime.Now.AddMinutes(jwt.ExpiresTime),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)

                );
            // 生成Token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return TokenStr;
        }

        /// <summary>
        /// 随机字符串
        /// </summary>
        /// <param name="length"></param>
        /// <param name="availableChars"></param>
        /// <returns></returns>
        public static string GetRandomString(int length = 5, string availableChars = null)
        {
            if (availableChars == null) availableChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var id = new char[length];
            Random random = new Random();
            for (var i = 0; i < length; i++)
            {
                id[i] = availableChars[random.Next(0, availableChars.Length)];
            }
            return new string(id);
        }
    }
}
